<script setup lang="ts">
import {
  Search2 as AppNutIconSearch2,
  HorizontalN as AppNutIconHorizontalN,
} from '@nutui/icons-vue-taro';
import dayjs from 'dayjs';
import { onMounted } from 'vue';
import { getCurrentInstance, setNavigationBarTitle, navigateTo, reLaunch } from '@tarojs/taro';
import {
  ASSET_CHANGE_RECEIVE_STATUS,
  ASSET_CHANGE_RECEIVE_STATUS_COLOR,
  ASSET_CHANGE_RECEIVE_STATUS_BG_COLOR,
} from '/@/common/constant';
import { QUERY_CHANGE_RECEIVE_LIST } from '/@/api/modules/archive/archive-change-receive';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { appEvents } from '/@/utils/events';
import { state } from './state';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 页面类型
   * - default 档案领用
   * - sign-in 档案签收
   */
  pageType?: 'sign-in' | 'default';
};

const PAGE_TITLE = {
  default: '领用',
  'sign-in': '签收',
};

/**
 * @description 列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;

  QUERY_CHANGE_RECEIVE_LIST({
    comQuery: { page, pageSize },
    appUserId: state.appUserId,
    keyword: state.keyword,
    status: state.status,
    signTag: state.pageType === 'sign-in' ? 1 : undefined,
  })
    .then((res) => {
      state.loading = false;

      if (
        state.activePage >=
        (res.comQuery.pageCount ||
          (res.comQuery.totalCount as number) / (res.comQuery.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.changeDtoList || !res.changeDtoList.length) return;

      res.changeDtoList.forEach((item) => state.list.push(item));

      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage);
}

onMounted(() => {
  state.pageType = params.pageType || 'default';
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.status = { default: [1, 2, 3, 4], 'sign-in': [3] }[state.pageType];
  state.list = [];

  setNavigationBarTitle({
    title: `档案${PAGE_TITLE[state.pageType]}`,
  });

  LOGIN_APP().then((res) => {
    state.appUserId = res.sysUserDto.id || '';
    onLoading();
  });

  appEvents.on('assetReceiveItemStatusChange', ({ id, changeStatus }) => {
    state.list[
      state.list.findIndex((item) => {
        return item.id === id;
      })
    ].changeStatus = changeStatus;
  });
});
</script>

<template>
  <view class="asset-receive-list app-page--1">
    <app-navbar :title="`档案${PAGE_TITLE[state.pageType]}`" />
    <nut-tabs
      model-value="record"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'push') {
            reLaunch({ url: '/pages/archive-manage/receive-edit/index' });
          }
        }
      "
    >
      <nut-tab-pane :title="`新增${PAGE_TITLE[state.pageType]}`" pane-key="push" />
      <nut-tab-pane :title="`${PAGE_TITLE[state.pageType]}列表`" pane-key="record" />
    </nut-tabs>
    <nut-searchbar
      v-model="state.keyword"
      :placeholder="`请输入${PAGE_TITLE[state.pageType]}人/${PAGE_TITLE[state.pageType]}单号`"
      @search="
        () => {
          state.activePage = 1;
          state.finished = false;
          state.list = [];
          onLoading();
        }
      "
      @clear="
        () => {
          state.activePage = 1;
          state.finished = false;
          state.list = [];
          onLoading();
        }
      "
    >
      <template v-slot:leftin>
        <app-nut-icon-search2 />
      </template>
      <template v-if="state.pageType === 'default'" v-slot:rightout>
        <nut-popover
          v-model:visible="state.filterPopoverVisible"
          location="bottom-end"
          :list="[
            { key: [1, 2, 3, 4], name: '全部' },
            ...Object.entries(ASSET_CHANGE_RECEIVE_STATUS).map((item) => {
              return { key: [Number(item[0])], name: item[1] };
            }),
          ]"
          @choose="
            (item) => {
              state.status = item.key;
              state.activePage = 1;
              state.finished = false;
              state.list = [];
              onLoading();
            }
          "
        >
          <template #reference>
            <view class="asset-receive-list__filter-wrapper">
              <app-nut-icon-horizontal-n class="asset-receive-list__filter-icon" />
              <text>筛选</text>
            </view>
          </template>
        </nut-popover>
      </template>
    </nut-searchbar>
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="asset-receive-list__wrapper">
        <view
          class="asset-receive-item"
          v-for="item in state.list"
          :key="item.id"
          @click="navigateTo({ url: `pages/archive-manage/receive-detail/index?id=${item.id}` })"
        >
          <view class="asset-receive-item__header">
            <view class="asset-receive-item__header--left">{{ item.changeCode }}</view>
            <view class="asset-receive-item__header--right">
              <text
                class="asset-receive-item__status"
                :style="{
                  color: item.changeStatus
                    ? ASSET_CHANGE_RECEIVE_STATUS_COLOR[item.changeStatus]
                    : '#999',
                  backgroundColor: item.changeStatus
                    ? ASSET_CHANGE_RECEIVE_STATUS_BG_COLOR[item.changeStatus]
                    : '#999',
                }"
              >
                {{ item.changeStatus ? ASSET_CHANGE_RECEIVE_STATUS[item.changeStatus] : '-' }}
              </text>
            </view>
          </view>
          <nut-row gutter="10">
            <nut-col span="12">
              领用时间:&nbsp;&nbsp;{{
                item.changeTime ? dayjs(Number(item.changeTime)).format('YYYY/MM/DD') : '-'
              }}
            </nut-col>
            <nut-col span="12">领用部门:&nbsp;&nbsp;{{ item.applicantDeptName || '-' }}</nut-col>
          </nut-row>
          <nut-row gutter="10">
            <nut-col span="24">领用人:&nbsp;&nbsp;{{ item.applicantName || '-' }}</nut-col>
          </nut-row>
        </view>
      </view>

      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
